// pages/menu/menu.js
import { createStoreBindings } from 'mobx-miniprogram-bindings'
import { store } from '../../store/store'
Page({
  onLoad(options) {
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: ['foodList', 'foodCateSum', 'foodDetail', 'totalCost', 'shoppingCar', 'lastCar'], //一加载就获取共享数据？？？
    })
    let authorization = wx.getStorageSync('Authorization') ? wx.getStorageSync('Authorization') : ''
    wx.request({
      url: 'https://www.liahnu.top/apis/shoppingCart/my',
      method: 'GET',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        Authorization: authorization,
      },
      success: (res) => {
        this.setData({
          lastCar: res.data.data,
        })
        // console.log(this.data.lastCar)
        let nienie = 0
        for (let i = 0; i < this.data.lastCar.length; i++) {
          if (this.data.lastCar[i].count > 0) {
            this.data.shoppingCar.push({
              name: this.data.lastCar[i].dish.description,
              number: this.data.lastCar[i].count,
              price: this.data.lastCar[i].dish.price,
              foodId: this.data.lastCar[i].dish.id,
            })
            nienie += this.data.lastCar[i].dish.price * this.data.lastCar[i].count
          }
        }
        // console.log(nienie);
        this.setData({
          totalCost: nienie.toFixed(2),
        })
      },
    })
  },
  options: { styleIsolation: 'shared' },
  data: {
    active: 0,
    currentTab: 0,
    show: false,
    catePage: 1, //这个是当前侧边栏对应右边菜品的id
    tabSw: 1, //控制标签栏的切换
    foodNow: 1, //当前第几个菜品
    priceCount: 0, //计算当前商品的总价格
    priceSingle: 0, //当前商品单个价格
    foodCount: 0, //计算当前商品选了多少个
    detailShow: false, //详细信息栏显示
    carIndex: 0, //购物车项目下标
    oldOrder: [], //用于修改和覆盖新的订单
    newOrder: [], //用于获取数量不为0的数据
  },
  switchNav: function (e) {
    //点击侧边栏事件
    let page = this
    let id = e.target.id
    if (this.data.currentTab == id) {
      return false
    } else {
      page.setData({
        currentTab: id,
        catePage: id - -1,
      }),
        wx.request({
          url: 'https://www.liahnu.top/apis/dish/getDish',
          method: 'GET',
          data: {
            categoryId: this.data.catePage,
            shopId: 1,
          },
          success: (res) => {
            console.log(res.data.data)
            res.data.data.forEach(function (item) {
              if (item.image != null) {
                item.image = 'https://www.liahnu.top/picture/uploads/' + item.image
              }
            })
            this.setData({ foodDetail: res.data.data })
          },
        })
      // console.log(this.data.catePage);
    }
    page.setData({
      active: id,
    })
  },
  nienie(event) {
    //切换顶部tab栏内容
    this.setData({
      tabSw: event.target.dataset.now,
    })
  },
  addShoppingCar(event) {
    //点击添加购物车
    if (this.data.foodCount > 0) {
      let sw = 0
      for (let i = 0; i < this.data.shoppingCar.length; i++) {
        //解决菜名重复
        if (this.data.shoppingCar[i].name === event.target.dataset.name) {
          this.data.shoppingCar[i].number -= -this.data.foodCount
          sw = 1
          break
        }
      }
      if (sw == 0) {
        this.data.shoppingCar.push({
          name: event.target.dataset.name, //商品名字
          number: this.data.foodCount, //商品数量
          price: this.data.priceSingle, //商品单价
          // id: this.data.carIndex,
          // totalCost: (this.data.foodCount * this.data.priceSingle).toFixed(2),
          foodId: event.target.dataset.id, //商品id
        })
      }
    }
    this.setData({
      show: false,
      totalCost: (this.data.priceCount - -this.data.totalCost).toFixed(2),
      priceCount: 0,
      foodCount: 0,
      carIndex: this.data.carIndex - -1,
    })
    let authorization = wx.getStorageSync('Authorization') ? wx.getStorageSync('Authorization') : ''
    wx.request({
      url: 'https://www.liahnu.top/apis/shoppingCart/add',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        Authorization: authorization,
      },
      data: {
        count: this.data.foodCount,
        dishId: event.target.dataset.id,
      },
      success: (res) => {},
    })
    // getApp().request(POST,'/apis/shoppingCart/add',{count: this.data.foodCount,dish_id: event.target.dataset.id,})
  },
  onChange(event) {
    //选规格里面的步进器的事件
    this.setData({
      priceCount: (event.detail * event.target.dataset.number).toFixed(2),
      foodCount: event.detail,
      priceSingle: event.target.dataset.number,
    })
  },
  getInfo() {
    //进入这个页面后马上请求数据
    wx.request({
      url: 'https://www.liahnu.top/apis/category/getCategory',
      method: 'GET',
      data: {
        shopId: 1,
      },
      success: (res) => {
        this.setData({ foodList: res.data.data, foodCateSum: res.data.total })
      },
    }),
      wx.request({
        url: 'https://www.liahnu.top/apis/dish/getDish',
        method: 'GET',
        data: {
          categoryId: 1,
          shopId: 1,
        },
        success: (res) => {
          res.data.data.forEach(function (item) {
            if (item.image != null) {
              item.image = 'https://www.liahnu.top/picture/uploads/' + item.image
            }
          })
          this.setData({ foodDetail: res.data.data })
        },
      })
  },
  showPopup(event) {
    //显示菜品弹出层
    this.setData({
      show: true,
      foodNow: event.target.dataset.foodnow,
    })
    // console.log(this.data.foodNow);
  },
  onClose() {
    //关闭菜品弹出层事件
    this.setData({
      show: false,
      priceCount: 0,
      foodCount: 0,
    })
  },
  detailClose() {
    //关闭详细弹出层事件
    this.setData({
      detailShow: false,
    })
  },
  detailOpen() {
    //打开详细弹出层事件
    this.setData({
      oldOrder: this.data.shoppingCar,
      detailShow: true,
    })
  },
  orderChange(event) {
    //修改订单事件
    this.data.oldOrder[event.target.dataset.new].number = event.detail
    this.data.oldOrder[event.target.dataset.new].totalCost = event.detail * this.data.oldOrder[event.target.dataset.new].price
    let newcost = 0
    for (let i = 0; i < this.data.oldOrder.length; i++) {
      //计算总价
      newcost -= -this.data.oldOrder[i].number * this.data.oldOrder[i].price
    }
    this.setData({
      totalCost: newcost.toFixed(2),
    })
    // getApp().request(PUT,'/apis/shoppingCart/update',{count: event.detail,dish_id: this.data.oldOrder[event.target.dataset.new].foodId,})
    let authorization = wx.getStorageSync('Authorization') ? wx.getStorageSync('Authorization') : ''
    wx.request({
      url: 'https://www.liahnu.top/apis/shoppingCart/update',
      method: 'PUT',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        Authorization: authorization,
      },
      data: {
        count: event.detail,
        dish_id: this.data.oldOrder[event.target.dataset.new].foodId,
      },
      success: (res) => {},
    })
  },
  finish() {
    //确定修改订单事件
    for (let i = 0; i < this.data.oldOrder.length; i++) {
      if (this.data.oldOrder[i].number > 0) {
        this.data.newOrder.push(this.data.oldOrder[i])
      }
    }
    this.setData({
      shoppingCar: this.data.newOrder, //将当前修改过的订单覆盖掉最终的
      detailShow: false,
      newOrder: [],
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getInfo()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.storeBindings.destroyStoreBindings()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
  onClickShow() {
    this.setData({ detailShow: true })
  },

  onClickHide() {
    // this.setData({ detailShow: false })
  },
})
